package com.bugsnag.ohos.reactnative;

import ohos.global.i18n.text.MeasureOptions;


import com.bugsnag.ohos.Client;
import com.bugsnag.ohos.StateEvent;
import com.bugsnag.ohos.internal.StateObserver;

import java.util.HashMap;
import java.util.Map;

/**
 * Listens for changes in the user, context, and metadata, then informs the JS layer
 * of any state alterations.
 */
public class BugsnagReactNativeBridge implements StateObserver {

    private Client client;
    private Function1 cb;

    public BugsnagReactNativeBridge(Client client, Function1 cb) {
        super();
        this.client = client;
        this.cb = cb;
    }

    @Override
    public void onStateChange(StateEvent event) {
        MessageEvent msgEvent = null;
        if (event instanceof StateEvent.UpdateContext) {
            msgEvent = new MessageEvent("ContextUpdate",((StateEvent.UpdateContext) event).context);
        } else if (event instanceof StateEvent.AddMetadata || event instanceof StateEvent.ClearMetadataSection || event instanceof StateEvent.ClearMetadataValue) {
            msgEvent = new MessageEvent("MetadataUpdate", client.getMetadata());
        } else if (event instanceof StateEvent.UpdateUser) {
            Map map = new HashMap<>();
            map.put("id", ((StateEvent.UpdateUser) event).user.id);
            map.put("email", ((StateEvent.UpdateUser) event).user.email);
            map.put("name", ((StateEvent.UpdateUser) event).user.name);
            msgEvent = new MessageEvent("UserUpdate", map);
        }
        if (msgEvent != null) {
            cb.invoke(msgEvent);
        }
    }

    public interface Function1{
         MeasureOptions.Unit invoke(MessageEvent messageEvent);
    }
}
